package com.shqcjd.preinstallglass.util;

import android.Manifest;
import android.app.Activity;

import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.model.eventbus.CreateVideotape;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoEncoderConfiguration;
import io.reactivex.functions.Consumer;

/**
 * Created by sy on 2019/6/28.
 */

public class VideotapeUtil {
    private Activity activity;
    private CreateVideotape videotape;
    private RtcEngine mRtcEngine;
    private Boolean isVideotape;
    private OnVideotapeListener onVideotapeListener;
    private OnFinishVideotapeListener onFinishVideotapeListener;
    private OnEngineInterface onEngineInterface;
    private static final VideotapeUtil instance = new VideotapeUtil();

    private VideotapeUtil() {}

    public static VideotapeUtil getInstance() {

        return instance;

    }


    /**
     * 定义创建录像成功回调接口
     */
    public interface OnVideotapeListener{
        void onVideotape(String channel, int uid, int elapsed);
    }

    /**
     * 定义关闭全程录像回调
     */
    public interface OnFinishVideotapeListener{
        void onInitFinish();
        void onFinishVideotape();
    }

    /**
     * 定义sdk事件接口回调
     */
    public interface OnEngineInterface{
        void onUserJoined(int uid, int elapsed);
        void onUserOffline(int uid, int reason);
    }


    /**
     * 创建全程录像
     * @param activity
     * @param videotape
     * @param onVideotapeListener
     */
    public void createVideotape(Activity activity,boolean isVideotape,CreateVideotape videotape,OnVideotapeListener onVideotapeListener){
        this.activity = activity;
        this.videotape = videotape;
        this.onVideotapeListener = onVideotapeListener;
        this.isVideotape = isVideotape;

        RxPermissions permissions = new RxPermissions(activity);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initAgoraEngineAndJoinChannel();
                        } else {
                            ToastUtils.showShort(activity, "缺少全程录像必要权限");
                        }
                    }
                });

    }

    /**
     * 创建全程录像
     * @param activity
     * @param videotape
     */
    public void createVideotape(Activity activity,boolean isVideotape,CreateVideotape videotape){
        this.activity = activity;
        this.videotape = videotape;
        this.isVideotape = isVideotape;

        RxPermissions permissions = new RxPermissions(activity);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initAgoraEngineAndJoinChannel();
                        } else {
                            ToastUtils.showShort(activity, "缺少全程录像必要权限");
                        }
                    }
                });

    }

    /**
     * 关闭全程录像
     * @param onFinishVideotapeListener
     */
    public void finishVideotape(OnFinishVideotapeListener onFinishVideotapeListener){
        this.onFinishVideotapeListener = onFinishVideotapeListener;
        onFinishVideotapeListener.onInitFinish();
        if (mRtcEngine != null) {
            Logger.i("创建全程录像 leaveChannel：关闭");
            mRtcEngine.leaveChannel();//离开频道
        } else {
            onFinishVideotapeListener.onFinishVideotape();
        }
    }

    /**
     * 设置sdk事件回调
     * @param onEngineInterface
     */
    public void setOnEngineInterface(OnEngineInterface onEngineInterface){
        this.onEngineInterface = onEngineInterface;
    }


    private void initAgoraEngineAndJoinChannel() {
        //初始化视频
        initializeAgoraEngine();     // 步骤1
        setupVideoProfile();         // 步骤2
        joinChannel();
    }

    private void setupVideoProfile() {
        mRtcEngine.enableVideo();

//        mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, false);//视频分辨率

        VideoEncoderConfiguration.VideoDimensions vd_1280x720 = VideoEncoderConfiguration.VD_1280x720;
        VideoEncoderConfiguration.FRAME_RATE frameRateFps15 = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15;
        int standardBitrate = VideoEncoderConfiguration.STANDARD_BITRATE;
        VideoEncoderConfiguration.ORIENTATION_MODE orientationModeAdaptive = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE;
        VideoEncoderConfiguration videoEncoderConfiguration = new VideoEncoderConfiguration(vd_1280x720, frameRateFps15, standardBitrate, orientationModeAdaptive);
        mRtcEngine.setVideoEncoderConfiguration(videoEncoderConfiguration);
    }

    private void initializeAgoraEngine() {
        mRtcEngine = MyApp.the().getmRtcEngine();
//        mRtcEngine.addHandler(iRtcEngineEventHandler);
        MyApp.the().setOnAgoraEngineInterface(new MyApp.OnAgoraEngineInterface() {
            @Override
            public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {

            }

            @Override
            public void onUserJoined(int uid, int elapsed) {
                Logger.i("VideotapeUtil onUserJoined1");
                if (!isVideotape) {//远程指导时监听
                    Logger.i("VideotapeUtil onUserJoined2");
                    onEngineInterface.onUserJoined(uid,elapsed);
                }
            }

            @Override
            public void onUserOffline(int uid, int reason) {
                Logger.i("VideotapeUtil onUserOffline1");
                if (!isVideotape) {//远程指导
                    Logger.i("VideotapeUtil onUserOffline2");
                    onEngineInterface.onUserOffline(uid,reason);
                }
            }

            @Override
            public void onUserMuteVideo(int uid, boolean muted) {

            }

            @Override
            public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
                Logger.i("VideotapeUtil onJoinChannelSuccess1："+channel+" 当前:"+UIUtils.getTopActivity(activity));
                //加入成功后请求创建远程指导
//                if (UIUtils.getTopActivity(activity).equals(activity.getComponentName().getClassName())) {
                if (isVideotape) {//全程录像
                    Logger.i("VideotapeUtil onJoinChannelSuccess2："+channel+" getCurrentActivity:");
                    onVideotapeListener.onVideotape(channel, uid, elapsed);
                }
//                }
            }

            @Override
            public void onLeaveChannel(IRtcEngineEventHandler.RtcStats stats) {
                Logger.i("VideotapeUtil onLeaveChannel1：当前:"+UIUtils.getTopActivity(activity));
//                if (UIUtils.getTopActivity(activity).equals(activity.getComponentName().getClassName())) {
                if (isVideotape) {//远程指导
                    Logger.i("VideotapeUtil onLeaveChannel2：:");
                    onFinishVideotapeListener.onFinishVideotape();
                }
//                }
            }

            @Override
            public void onError(int err) {

            }
        });
        if (mRtcEngine != null) {
            mRtcEngine.setLogFile("/sdcard/sdklog.txt");
        }
    }

    private void joinChannel() {
        mRtcEngine.leaveChannel();
        //保存打开全程录像记录
        int i = mRtcEngine.joinChannel(null, videotape.roomId, "Extra Optional Data", videotape.userId);// if you do not specify the uid, we will generate the uid for you

        if (i == 0) {//加入成功
            setLocalAudio(!isVideotape);//开/关本地音频采集
        }
        Logger.i("创建全程录像 joinChannel："+i+"  roomId:"+videotape.roomId);
    }


    /**
     * 开/关本地音频采集。需要在 joinChannel 之后调用才能生效
     * @param b
     */
    private void setLocalAudio(boolean b) {
        mRtcEngine.enableLocalAudio(b);//开/关本地音频采集。需要在 joinChannel 之后调用才能生效
    }
}
